package com.example.tnot.api;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class JpegFrameDecoder {
    private ImageView targetView;
    private ProgressBar loadingPb;

    public JpegFrameDecoder(ImageView view, ProgressBar progressBar) {
        this.targetView = view;
        this.loadingPb = progressBar;
    }

    public void decodeAndShow(byte[] frameData) {
        if (frameData == null || frameData.length == 0) {
            Log.e("Decoder", "无效帧数据");
            return;
        }

        try {
            // 解码JPEG字节数组为Bitmap
            Bitmap bitmap = BitmapFactory.decodeByteArray(frameData, 0, frameData.length);
            if (bitmap != null) {
                // 在UI线程更新画面
                targetView.post(() -> {
                    targetView.setImageBitmap(bitmap);
                    // 隐藏加载动画（第一帧成功显示后）
                    if (loadingPb.getVisibility() == View.VISIBLE) {
                        loadingPb.setVisibility(View.GONE);
                    }
                });
            } else {
                Log.e("Decoder", "JPEG解码失败（可能格式不匹配）");
            }
        } catch (Exception e) {
            Log.e("Decoder", "解码异常: " + e.getMessage());
        }
    }
}